import { Component } from '@angular/core';
import { NavParams, ViewController, ModalController, AlertController } from 'ionic-angular';
import { TaskDetailService } from './detail.service';
import { Common } from '../../../providers/common';
import { Config } from '../../../providers/config';
import { ContactChoosePage } from '../../contact/choose/choose.component';
import { EmailDetailService } from '../../email/detail/detail.service';
import {Storage} from '@ionic/storage';
import _ from 'lodash';


@Component({
  selector: 'page-task-flowApproval',
  templateUrl: './flowApproval.html',
  providers: [TaskDetailService,EmailDetailService]
})
export class FlowApprovalPage {
	moa_page_name: any = "page-task-flowApproval";
  moa_page_explain: any = "流程送阅";

  // 送阅群体,如：张三,李四,王五
  wkiUserName;
  // 送阅群体ID 如：123,232,343
  wkiUserId = "";
  // 送阅意见
  wkiDesc = "";
  // 当前登录人ID
  loginId;
  // 业务ID
  bid = "";
  // 送阅标题
  wkiTitle = "";
  // 模版ID
  bomid = "";

  wkiLoginid = [];

  // 缓存通过组织树选择的人员
  // 结构如下：
  // [{
  //   empid:"A938493525",
  //   name:"冯镜蒯",
  //   orgid:"xtyfz",
  //   loginid:"fengjk",
  //   titleid:"ybyg"
  // },{}]
  defaultEmpByTree = [];

  // 是否选中 邮件送阅
  isChecked = false;

  //通知方式，isToRead送阅，isEmail邮件，isSMS短信
  notifyType = {
    isToRead: true,
    isEmail: false,
    isSMS: false
  };

  isPressSuccess = true;//催办提交是否成功

  constructor(
    public navParams: NavParams,
    public viewCtrl: ViewController,
    public modalCtrl: ModalController,
    public alertCtrl: AlertController,
    public detailService: TaskDetailService,
    public emailDetailService: EmailDetailService,
    public common: Common,
    public storage: Storage
  ) {
    this.loginId = this.navParams.get('loginId');
    this.bid = this.navParams.get('bid');
    this.wkiTitle = this.navParams.get('wkiTitle');
    this.bomid = this.navParams.get('bomid');

  }

  complete() {
    this.dismiss({});
  }

  dismiss(data?: any) {
    // using the injected ViewController this page
    // can "dismiss" itself and pass back data
    this.viewCtrl.dismiss(data);
  }

  /**
   * [chooseUser 选择送阅人]
   */
  chooseUser() {
    let that = this;
    let modal = this.modalCtrl.create(ContactChoosePage, {
      selected: this.defaultEmpByTree
    });

    modal.present();
    modal.onWillDismiss((data: any[]) => {
      //console.info("##送阅人员：" + data);
      if (data) {
        that.defaultEmpByTree = data;
        that.wkiUserName = _.map(data, "name");
        that.wkiLoginid = _.map(data, "loginid");
        that.wkiUserId = this.common.formatContactListData(data);
      }
    });
  }

  /**
   * [checkConfirmData 送阅数据提交校验]
   */
  checkConfirmData() {
    let retVal: any = {
      result: true, // 是否校验通过
      message: "您确认提交？" // 提示信息
    };

    if (this.bid == "" || this.wkiTitle == "" || this.bomid == "") {
      retVal.result = false;
      retVal.message = "数据有异常,提交失败！";
    } else if (this.wkiUserId.length < 1) {
      retVal.result = false;
      retVal.message = "送阅群体不能为空！";
    }

    if (!this.notifyType.isToRead && !this.notifyType.isEmail && !this.notifyType.isSMS) {
      retVal.result = false;
      retVal.message = "请至少选择一种通知方式";
    }

    return retVal;
  }

  /**
   * [update 更新送阅]
   */
  update() {

    if (this.notifyType.isToRead) {
        this.toRead();
    }

    if (this.notifyType.isEmail) {
        this.sendEmail();
    }

    if (this.notifyType.isSMS) {
        this.sendSMS();
    }

    if (this.isPressSuccess) {
      let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
        title: "提示",
        message: "送阅提交成功！",
        buttons: [
          {
            text: "确定",
            handler: () => {
              this.dismiss();
            }
          }
        ]
      });
      alert.present();
    }
  }

  /**
   * 流程送阅
   */
  toRead() {
    let that = this;
    let params = {
      "loginId": "fengjk",
      "bid": this.bid,
      "wkiTitle": this.wkiTitle,
      "bomid": this.bomid,
      "wkiUser": this.wkiUserId,
      "wkiDesc": this.wkiDesc
    };
    console.log("##送阅提交：");
    console.log(params);

    this.detailService.addApproval(params).subscribe(data => {
      //console.log("## 送阅返回信息");
      //console.log(data);
      if (data.msg == "成功！" && data.code == "0") {

      } else {
        this.isPressSuccess = false;
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "异常信息提示",
          message: data.exception,
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
                //console.log('Cancel clicked');
              }
            }
          ]
        });
        alert.present();
      }
    });
  }

  sendEmail() {
    // /Legion/Platform/FlowsComponent/BoFProIndex.jsp?bosid=900902&bomid=t_caipx_test
    var sendBody = {
      bostitle: this.wkiTitle,
      content: this.wkiDesc + '<a href="/Legion/Platform/FlowsComponent/BoFProIndex.jsp?bosid=' + this.bid + '&amp;bomid=t_caipx_test" data-ke-src="/Legion/Platform/FlowsComponent/BoFProIndex.jsp?bosid=' +  this.bid +'&amp;bomid=t_caipx_test" target="_blank">点击查看详细</a>',
      isreceipt: 0,
      login: "",
      otherlist: "",
      recievelist: this.wkiUserId,
      secretlist: "",
      urgency: 9
    };

    this.emailDetailService.sendEmail(sendBody).subscribe(data=>{
      if (data) {

      } else {
        this.isPressSuccess = false;
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "异常信息提示",
          message: "送阅邮件发送失败",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
                //console.log('Cancel clicked');
              }
            }
          ]
        });
        alert.present();
      }
    });
  }

  sendSMS() {
    let content = "您OA系统中有一份 " + this.wkiTitle
      + " 文件送阅事项！请登录OA系统处理！具体的送阅意见为：" + this.wkiDesc;

    this.storage.get("contact-user-list").then(u => {
      _.forEach(this.wkiLoginid, userid => {
        let temp = _.find(u, ["loginid", userid]);
        let params = {
          "mobile": temp["empmobile"],
          "content": content
        };

        this.detailService.sendSMS(params)
          .subscribe(result => {
            if (!result.isSuccess) {
              let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
                title: "异常信息提示",
                message: "给 " + temp["emname"] + " 的手机短信发送失败",
                buttons: [
                  {
                    text: "确定",
                    role: 'cancel',
                    handler: () => {
                      //console.log('Cancel clicked');
                    }
                  }
                ]
              });
              alert.present();
            }
          });
      });
    });
  }

  /**
   * [confirm 提交送阅]
   */
  confirm() {
    let checkResult = this.checkConfirmData();
    if (!checkResult.result) {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: checkResult.message,
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
              //console.log('Cancel clicked');
            }
          }
        ]
      });
      alert.present();
    } else {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: checkResult.message,
        buttons: [
          {
            text: '取消',
            role: 'cancel',
            handler: () => {
              //console.log('Cancel clicked');
            }
          },
          {
            text: "确定",
            handler: () => {
              this.update();
            }
          }
        ]
      });
      alert.present();
    }
  }

  // 各方式的勾选状态切换
  iocnCheck(type){
    switch (type) {
      case "isEmail":
        this.notifyType.isEmail = !this.notifyType.isEmail;
        break;
      case "isSMS":
        this.notifyType.isSMS = !this.notifyType.isSMS;
        break;
    }
  }

}
